//    Copyright (C) Kherty.  All rights reserved.
using System.Collections.Generic;

namespace OpenLS.Spreadsheet
{
    static class TableFunctions
    {
        public static TableFunction None { get { return new TableFunction(t => { }, (a, b) => { }); } }

        public static TableFunction ClearAndCopyTables
        {
            get
            {
                return new TableFunction(
                    ClearTables
                    , CopyTables);
            }
        }
        public static TableFunction ClearAndCopyTablesAndConditionalFormatting
        {
            get
            {
                return new TableFunction(
                    ClearTables
                    , CopyTablesAndConditionalFormatting);
            }
        }
        public static void CopyTablesAndConditionalFormatting(Range source, Range destination)
        {
            CopyTables(source, destination);
            CopyDataValidation(source, destination);
        }

        private static void ClearTables(Range r)
        {
            var tables = new List<Table>(r.Worksheet.Tables);
            tables = tables.FindAll(t => r.Contains(t.Range));
            foreach (var table in tables)
            {
                r.Worksheet.RemoveTable(table);
            }
        }

        private static void CopyTables(Range source, Range destination)
        {
            CellRelativeAddress offset = destination.TopLeftCell.Address - source.Worksheet.Selection.TopLeftCell.Address;
            List<Table> tables = new List<Table>(source.Worksheet.Tables).FindAll(t => source.Contains(t.Range));
            foreach (Table table in tables)
            {
                Range newRange = table.SimpleRange.ProjectedSimple(destination.Worksheet, offset);
                destination.Worksheet.AddTable(newRange, table.Style, table.Name+"_bis", table.Comment, table.IsPublic, table.IsReadOnly, table.AllowsUpdate, table.AllowsDelete, table.AllowsInsert);
            }
        }
        private static void CopyDataValidation(Range source, Range destination)
        {
            CellRelativeAddress offset = destination.TopLeftCell.Address - source.Worksheet.Selection.TopLeftCell.Address;
            List<DataValidation> dataValidations =
                Enumerable.ToList(Enumerable.Where(source.Worksheet.DataValidations,
                                                   dv => Range.Intersects(source, dv.Range)));
            foreach (var dataValidation in dataValidations)
            {
                var newDataValidation = dataValidation.Projected(destination.Worksheet, offset);
                destination.Worksheet.DataValidations.Add(newDataValidation);
            }
        }
    }
}